<!--
 *Author：jxx
 *Contact：283591387@qq.com
 *业务请在@/extension/wms/taskcode/taskmanagement.jsx或taskmanagement.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://v3.volcore.xyz/docs/view-grid、https://v3.volcore.xyz/docs/web
 -->
<template>
    <view-grid ref="grid"
               :columns="columns"
               :detail="detail"
               :details="details"
               :editFormFields="editFormFields"
               :editFormOptions="editFormOptions"
               :searchFormFields="searchFormFields"
               :searchFormOptions="searchFormOptions"
               :table="table"
               :extend="extend"
               :onInit="onInit"
               :onInited="onInited"
               :searchBefore="searchBefore"
               :searchAfter="searchAfter"
               :addBefore="addBefore"
               :updateBefore="updateBefore"
               :rowClick="rowClick"
               :modelOpenBefore="modelOpenBefore"
               :modelOpenAfter="modelOpenAfter">
        <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
        <template #gridHeader>
        </template>
    </view-grid>

    <!-- 审核弹窗 -->
    <el-dialog v-model="auditDialogVisible" title="审核" width="460px">
        <div style="line-height: 28px;">
            <div>任务编号：{{ auditRow?.TaskNo }}</div>
            <div>任务名称：{{ '发货' }}</div>
        </div>
        <div style="margin-top: 12px;">
            <el-radio-group v-model="auditDecision">
                <el-radio label="agree">同意</el-radio>
                <el-radio label="reject">拒绝</el-radio>
            </el-radio-group>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="onAuditCancel">取消</el-button>
                <el-button type="primary" @click="onAuditSave">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang="jsx">
    import extend from "@/extension/wms/taskcode/taskmanagement.jsx";
    import viewOptions from './taskmanagement/options.js'
    import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
    const grid = ref(null);
    const { proxy } = getCurrentInstance()
    //http请求，proxy.http.post/get
    const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())

    let gridRef;//对应[表.jsx]文件中this.使用方式一样
    // 审核对话框状态
    const auditDialogVisible = ref(false)
    const auditDecision = ref('agree')
    const auditRow = ref(null)

    const openAudit = (row) => {
        auditRow.value = row
        auditDecision.value = 'agree'
        auditDialogVisible.value = true
    }

    const onAuditCancel = () => {
        auditDialogVisible.value = false
    }

    const onAuditSave = async () => {
        if (!auditRow.value) return
        try {
            // 同意/拒绝后更新待办与状态
            const toDo = 2 // 已处理
            const status = 2 // 已审核（同意/拒绝由前端显示 _auditAgree 区分）
            const res = await proxy.http.post('api/taskmanagement/update', {
                mainData: {
                    TaskId: auditRow.value.TaskId,
                    To_doList: toDo,
                    ProcessingStatus: status
                },
                detailData: [],
                delKeys: []
            })
            if (res && res.status) {
                proxy.$message.success(res.message || '审核成功')
                
                // 创建消息通知
                await createNotification(auditRow.value, auditDecision.value)
                
                // 本地刷新展示
                auditRow.value.To_doList = toDo
                auditRow.value.ProcessingStatus = status
                auditRow.value._auditAgree = auditDecision.value === 'agree'
                gridRef?.search && gridRef.search()
                auditDialogVisible.value = false
            } else {
                proxy.$message.error(res?.message || '审核失败')
            }
        } catch (e) {
            proxy.$message.error('审核异常：' + (e?.message || ''))
        }
    }
    
    /**
     * 创建消息通知
     */
    const createNotification = async (task, decision) => {
        try {
            const decisionText = decision === 'agree' ? '已同意' : '已拒绝'
            const notificationData = {
                notification_title: `任务审核通知 - ${decisionText}`,
                notification_description: `任务编号：${task.TaskNo}，任务名称：发货，审核结果：${decisionText}`,
                notification_messagetype: '任务审核',
                notification_tag: decision === 'agree' ? 'success' : 'warning',
                notification_routepath: '/taskmanagement',
                notification_routequery: JSON.stringify({ taskId: task.TaskId }),
                notification_isread: 0, // 未读
                notification_userid: null, // 全局消息
                notification_createdate: new Date().toISOString()
            }
            
            await proxy.http.post('api/Sys_Notification/add', {
                mainData: notificationData,
                detailData: [],
                delKeys: []
            })
            
            console.log('消息通知创建成功')
        } catch (e) {
            console.error('创建消息通知失败：', e)
        }
    }
    //生成对象属性初始化
    const onInit = async ($vm) => {
        gridRef = $vm;
        //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
        //更多属性见：https://v3.volcore.xyz/docs/view-grid
        // 列格式化与操作列
        const taskNameCol = columns.find(c => c.field === 'TaskName')
        if (taskNameCol) {
            taskNameCol.formatter = () => '发货'
        }
        const todoCol = columns.find(c => c.field === 'To_doList')
        if (todoCol) {
            todoCol.formatter = (row) => {
                return row.To_doList === 1 ? '未处理' : (row.To_doList === 2 ? '已处理' : row.To_doList)
            }
        }
        const statusCol = columns.find(c => c.field === 'ProcessingStatus')
        if (statusCol) {
            statusCol.formatter = (row) => {
                if (row.ProcessingStatus === 1) return '待审核'
                if (row.ProcessingStatus === 2) {
                    if (row._auditAgree === true) return '已同意'
                    if (row._auditAgree === false) return '已拒绝'
                    // 未持久化的情况(刷新后无本地标记)
                    return '已处理'
                }
                return row.ProcessingStatus
            }
        }
        // 操作列
        const hasAction = columns.some(c => c.field === '_actions')
        if (!hasAction) {
            columns.push({
                field: '_actions',
                title: '操作',
                width: 120,
                align: 'center',
                fixed: 'right',
                render: (h, { row }) => {
                    return (
                        <el-button type="primary" size="small" onClick={() => openAudit(row)}>审核</el-button>
                    )
                }
            })
        }
    }
    //生成对象属性初始化后,操作明细表配置用到
    const onInited = async () => {
    }
    const searchBefore = async (param) => {
        //界面查询前,可以给param.wheres添加查询参数
        //返回false，则不会执行查询
        return true;
    }
    const searchAfter = async (rows, result) => {
        return true;
    }
    const addBefore = async (formData) => {
        //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
        return true;
    }
    const updateBefore = async (formData) => {
        //编辑保存前formData为对象，包括明细表、删除行的Id
        return true;
    }
    const rowClick = ({ row, column, event }) => {
        //查询界面点击行事件
        // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    }
    const modelOpenBefore = async (row) => {//弹出框打开后方法
        return true;//返回false，不会打开弹出框
    }
    const modelOpenAfter = (row) => {
        //弹出框打开后方法,设置表单默认值,按钮操作等
    }
    //监听表单输入，做实时计算
    //watch(() => editFormFields.字段,(newValue, oldValue) => {	})
    //对外暴露数据
    defineExpose({})
</script>
<style lang="less" scoped>
</style>
